package cn.tpshion.config.controller;

import cn.tpshion.config.common.Assert;
import cn.tpshion.config.common.AuthType;
import cn.tpshion.config.common.ErrorCode;
import cn.tpshion.config.common.R;
import cn.tpshion.config.domain.dto.AuthInfoDTO;
import cn.tpshion.config.domain.entity.AuthInfo;
import cn.tpshion.config.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 认证模块
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private ConfigurableEnvironment environment;

    /**
     * 服务认证
     * @param authInfoDTO
     * @return
     */
    @PostMapping("/login")
    public R login(@Validated @RequestBody AuthInfoDTO authInfoDTO){
        // 密码模式
        if(AuthType.PASSWORD.getType().equals(authInfoDTO.getType())){
            // 校验参数
            Assert.notEmpty(authInfoDTO.getUsername(),"用户名不能为空");
            Assert.notEmpty(authInfoDTO.getPassword(), "密码不能为空");
            AuthInfo authInfo = new AuthInfo();
            BeanUtils.copyProperties(authInfoDTO, authInfo);
            return R.success(authService.checkUser(authInfo),"认证成功");
        }

        // 授权码模式
        if(AuthType.CODE.getType().equals(authInfoDTO.getType())){
            Assert.notEmpty(authInfoDTO.getSecretkey(),"授权码模式，secretkey不能为空");
            return R.success(authService.checkCode(authInfoDTO.getSecretkey()),"认证成功");
        }

        // 其他模式直接认证失败
        return R.fail(ErrorCode.TOKEN_ERROR);
    }

    /**
     * 获取zookeeper地址
     * @return
     */
    @GetMapping("/getHost")
    public R<String> getHost(){
        String host = environment.getProperty("config.zookeeper.host",
                "localhost:2181");
        return R.success(host);
    }
}
